package com.taurus.myboard.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.taurus.myboard.entity.Role;
import com.taurus.myboard.entity.RoleMenu;
import com.taurus.myboard.mapper.RoleMapper;
import com.taurus.myboard.mapper.RoleMenuMapper;
import com.taurus.myboard.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kanten
 * @since 2023-06-07
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Override
    @Transactional
    public void addRole(Role role) {
        // 写入角色表
        this.baseMapper.insert(role);
        this.insertMenuIdList(role);
    }

    private void insertMenuIdList(Role role) {
        // 写入角色与菜单权限对应表
        if (null != role.getMenuIdList()) {
            for (Integer menuId : role.getMenuIdList()) {
                roleMenuMapper.insert(new RoleMenu(role.getRoleId(), menuId));
            }
        }
    }

    @Override
    public Role getRoleById(Integer id) {
        Role role = this.baseMapper.selectById(id);
        // 只查叶子节点
        List<Integer> menuIdList = roleMenuMapper.getLeafIdListByRoleId(id);
        role.setMenuIdList(menuIdList);
        return role;
    }

    @Override
    public void updateRole(Role role) {
        // 更新role
        this.baseMapper.updateById(role);
        // 插入rolemenu角色与菜单权限对应表
        if (null != role.getMenuIdList()) {
            LambdaQueryWrapper<RoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(RoleMenu::getRoleId, role.getRoleId());
            roleMenuMapper.delete(lambdaQueryWrapper);
            this.insertMenuIdList(role);
        }
    }

    @Override
    public void removeRoleById(Integer id) {
        this.baseMapper.deleteById(id);
        LambdaQueryWrapper<RoleMenu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(RoleMenu::getRoleId, id);
        this.roleMenuMapper.delete(lambdaQueryWrapper);
    }
}
